from django.utils.deprecation import MiddlewareMixin
from django.http import HttpResponseRedirect
from cms.models import PlatformLog
from front.models import User
from . import settings
import time


# 格式化时间戳
def formatTime(timestamp='', date=False):
    if timestamp:
        return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))
    else:
        if date:
            return time.strftime("%Y-%m-%d")
        else:
            return time.strftime("%Y-%m-%d %H:%M:%S")


# 用户登录验证
class MD1(MiddlewareMixin):
    urls = [
        '/',
        '/tests'
    ]
    cms_urls = [
        '/cms/index',
        '/cms/user',
        '/cms/advisory'
    ]

    def process_request(self, request):
        # 检测用户登录
        if request.path in self.urls:
            uid = request.COOKIES.get('uid')
            if not User.objects.filter(id=uid):
                return HttpResponseRedirect('/login')
        # 检测管理员登录
        if request.path in self.cms_urls:
            print(123123)
            secret_key = request.COOKIES.get('secret_key')
            if settings.SECRET_KEY != secret_key:
                return HttpResponseRedirect('/cms')

    def process_response(self, request, response):
        return response


# 平台统计：统计请求次数
class MD2(MiddlewareMixin):
    def process_request(self, request):
        log = PlatformLog.objects.filter(date=formatTime(date=True))
        if log:
            log = log.first()
            log.log['visit'] += 1
            log.save()
        else:
            PlatformLog.objects.create(date=formatTime(date=True),
                                       log={"register": 0, "visit": 1, "test": 0, "advisory": 0})

    def process_response(self, request, response):
        return response
